/**
 * 库存状态分析组件
 * 接口说明：
 * GET /admin/statistics/inventory/status
 * 参数：
 * - startDate: 开始日期 YYYY-MM-DD
 * - endDate: 结束日期 YYYY-MM-DD
 */

<template>
  <div class="inventory-status-container">
    <div class="charts-wrapper">
      <!-- 图书库存状态圆环图 -->
      <div class="chart-section">
        <div class="chart-header">
          <h3>图书库存状态分析</h3>
          <div class="total-books">
            总藏书量：{{ totalBooks }} 册
          </div>
        </div>
        <div ref="pieChartRef" class="pie-chart"></div>
      </div>
      
      <!-- 图书利用率仪表盘 -->
      <div class="chart-section">
        <div class="chart-header">
          <h3>图书利用率</h3>
        </div>
        <div ref="gaugeChartRef" class="gauge-chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick, onActivated } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getInventoryStatusStats } from '@/api/statistics'

/**
 * 图表实例引用
 */
let pieChart = null
let gaugeChart = null

/**
 * 图表DOM引用
 */
const pieChartRef = ref(null)
const gaugeChartRef = ref(null)

/**
 * 总藏书量
 */
const totalBooks = ref(0)

/**
 * 格式化日期为YYYY-MM-DD
 */
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 获取库存状态数据
 */
const fetchInventoryStatus = async (startDate, endDate) => {
  try {
    // 设置加载状态
    pieChart && pieChart.showLoading()
    gaugeChart && gaugeChart.showLoading()
    
    console.log('Fetching data with dates:', formatDate(startDate), formatDate(endDate))
    
    const response = await getInventoryStatusStats({
      startDate: formatDate(startDate),
      endDate: formatDate(endDate)
    })
    
    console.log('Response:', response)
    
    if (response.code === 0) {
      const { totalBooks: total, inventoryStatus } = response.data
      totalBooks.value = total
      updateChart(inventoryStatus)
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取库存状态数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    // 无论成功失败都关闭加载状态
    pieChart && pieChart.hideLoading()
    gaugeChart && gaugeChart.hideLoading()
  }
}

/**
 * 更新图表数据
 */
const updateChart = (inventoryStatus) => {
  if (!pieChart || !gaugeChart) return
  
  // 更新饼图
  const pieOption = {
    title: {
      text: '图书库存状态分析',
      left: 'center',
      top: 20
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}册 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '库存状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}册\n{d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: inventoryStatus.map(item => ({
          ...item,
          itemStyle: {
            color: item.name === '在库图书' ? '#67C23A' : 
                   item.name === '借出图书' ? '#409EFF' : 
                   item.name === '待维修图书' ? '#E6A23C' : 
                   item.name === '维修中图书' ? '#F56C6C' : '#909399'
          }
        }))
      }
    ]
  }
  
  // 计算图书利用率
  const totalCount = inventoryStatus.reduce((sum, item) => sum + item.value, 0)
  const borrowedCount = inventoryStatus.find(item => item.name === '借出图书')?.value || 0
  const utilizationRate = totalCount > 0 ? Math.round((borrowedCount / totalCount) * 100) : 0
  
  // 更新仪表盘
  const gaugeOption = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 8,
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#F56C6C'],  // 0-30% 红色
              [0.7, '#E6A23C'],  // 30-70% 黄色
              [1, '#67C23A']     // 70-100% 绿色
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          distance: -30,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: {
            color: '#fff',
            width: 4
          }
        },
        axisLabel: {
          color: 'inherit',
          distance: -40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}%',
          color: 'inherit',
          fontSize: 24,
          offsetCenter: [0, '20%']
        },
        data: [
          {
            value: utilizationRate,
            name: '图书利用率',
            title: {
              offsetCenter: [0, '-30%']
            }
          }
        ]
      }
    ]
  }
  
  pieChart.setOption(pieOption, true)
  gaugeChart.setOption(gaugeOption, true)
}

/**
 * 初始化图表
 */
const initChart = () => {
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
    pieChart.showLoading()
  }
  if (gaugeChartRef.value) {
    gaugeChart = echarts.init(gaugeChartRef.value)
    gaugeChart.showLoading()
  }
}

/**
 * 更新图表尺寸
 */
const handleResize = () => {
  pieChart && pieChart.resize()
  gaugeChart && gaugeChart.resize()
}

/**
 * 监听时间范围变化
 */
const props = defineProps({
  timeRange: {
    type: Array,
    default: () => []
  }
})

// 添加组件激活时的处理
const handleActivated = () => {
  console.log('InventoryStatus component activated')
  if (!props.timeRange || props.timeRange.length !== 2) {
    const now = new Date()
    const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
    const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    fetchInventoryStatus(startDate, endDate)
  } else {
    fetchInventoryStatus(props.timeRange[0], props.timeRange[1])
  }
}

watch(
  () => props.timeRange,
  (newRange) => {
    console.log('Time range changed:', newRange)
    if (newRange && newRange.length === 2) {
      fetchInventoryStatus(newRange[0], newRange[1])
    }
  }
)

onMounted(() => {
  // 确保DOM已经渲染
  nextTick(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })
})

// 添加 onActivated 生命周期钩子
onActivated(handleActivated)

onUnmounted(() => {
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
  if (gaugeChart) {
    gaugeChart.dispose()
    gaugeChart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.inventory-status-container {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
}

.charts-wrapper {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  min-height: 0;
}

.chart-section {
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.total-books {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
}

.pie-chart,
.gauge-chart {
  flex: 1;
  min-height: 400px;
}

@media screen and (max-width: 1200px) {
  .charts-wrapper {
    grid-template-columns: 1fr;
  }
}

@media screen and (max-width: 768px) {
  .inventory-status-container {
    padding: 16px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .pie-chart,
  .gauge-chart {
    min-height: 300px;
  }
}
</style> 